<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-form :model="queryParams" ref="queryForm"  v-show="showSearch" label-width="auto" @keyup.enter.native="handleQuery">
      <el-row :gutter="24" >
        <el-col :span="4">
          <el-form-item label="表名称" prop="tableNameKey">
            <el-input v-model="queryParams.tableNameKey" placeholder="请输入表名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="表描述" prop="tableCommentKey">
            <el-input v-model="queryParams.tableCommentKey" placeholder="请输入表描述" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="0px">
            <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="tool-bar-btn">
        <el-button type="primary" icon="el-icon-download" @click="handleGenTable()" v-hasPerms="['tool:gen:batchGenCode']">生成代码(zip)</el-button>
        <el-button type="info" icon="el-icon-upload"  @click="openImportTable" v-hasPerms="['tool:gen:importTable']">选择表结构</el-button>
        <el-button type="success" icon="el-icon-edit"  :disabled="single" @click="handleEditTable" v-hasPerms="['tool:gen:edit']">修改</el-button>
        <el-button type="danger" icon="el-icon-delete"  :disabled="multiple" @click="handleDelete" v-hasPerms="['tool:gen:remove']">删除</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </div>

    <!-- 列表区域 -->
    <selected-info :count="selectedRows.length" :onClearSelected="onClearSelected" />
    <el-table ref="dataTable" v-loading="loading" :data="dataList" stripe border @selection-change="onSelectChange">
      <el-table-column align="center"  type="selection" width="55" fixed></el-table-column>
      <el-table-column align="center"  label="序号" prop="id" width="50" fixed></el-table-column>
      <el-table-column align="center" label="表名称" prop="tableName" fixed :show-overflow-tooltip="true" width="240"/>
      <el-table-column align="center" label="表描述" prop="tableComment" fixed :show-overflow-tooltip="true" width="140"/>
      <el-table-column align="center" label="模块" prop="moduleName" width="120">
        <template slot-scope="{row}">
          <LamStatus :value="row.moduleName" :text="row.moduleName" :styleMap="moduleNameStyle" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="模板" width="150">
        <template slot-scope="{row}">
          <LamStatus :value="row.templateType" :text="row.templateTypeDictText" :styleMap="templateTypeStyle" :useTag="false"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="实体" prop="className" :show-overflow-tooltip="true" width="200"/>
      <el-table-column align="center" label="业务名" prop="businessName" :show-overflow-tooltip="true" width="180"/>
      <el-table-column align="center" label="功能名称" prop="functionName" :show-overflow-tooltip="true" width="180"/>
      <el-table-column align="center"  label="修改时间" prop="updateTime" width="170" />
      <el-table-column align="center"  label="操作" class-name="small-padding fixed-width" width="300" fixed="right">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-view" @click="handlePreview(row)" v-hasPerms="['tool:gen:preview']">预览</el-button>
          <el-button type="text" icon="el-icon-download" @click="handleGenTable(row)" v-hasPerms="['tool:gen:genCode']" >生成代码</el-button>
          <el-button type="text" icon="el-icon-edit" @click="handleEditTable(row)" v-hasPerms="['tool:gen:edit']">编辑</el-button>
          <el-dropdown v-hasPerms="['tool:gen:syncFromDb', 'tool:gen:remove']">
            <el-link type="primary" icon="el-icon-arrow-down" :underline="false" class="el-button--small">更多</el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPerms="['tool:gen:syncFromDb']">
                <el-button type="text" title="从数据库同步最新的表结构" icon="el-icon-refresh" @click="handleTableSync(row)" >同步</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-hasPerms="['tool:gen:remove']">
                <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)" >删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="!loading" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 预览界面 -->
    <preview ref="preview"/>

    <import-table ref="import" @ok="handleQuery" />

    <DownloadIframe ref="downloadIframe" />

  </div>
</template>

<style type="text/css" scoped>
</style>

<script>
import { httpGet, httpPost } from "@/api";
import importTable from "./importTable";
import preview from "./preview";
import { downloadFileHidden } from "@/utils/downloadUtil";
import { IndexListMixin } from '@/components/mixins/IndexListMixin';
import DownloadIframe from '@/components/download/DownloadIframe';

export default {
  name: "Gen",
  mixins:[IndexListMixin],
  components: {
    preview,
    importTable,
    DownloadIframe
  },
  data() {
    return {
      moduleNameStyle:{
        'system':'black',
        'schedule':'#9970db',
        'generator':'red',
        'stockBase':'#52c41a',
        'stockTrade':'blue',
      },
      templateTypeStyle:{
        'simple':'blue',
        'simpleTree':'#52c41a'
      },
      // 唯一标识符
      uniqueId: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: undefined,
        tableComment: undefined
      },
      url:{
        base: '/tool/gen/',
        list: '/tool/gen/list',
        batchGenCode:'/tool/gen/batchGenCode',
        genCode: '/tool/gen/genCode/',
        previewCode: '/tool/gen/preview/',
        syncFromDb: '/tool/gen/syncFromDb/'
      }
    };
  },
  created() {
    this.getList();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.getList();
    }
  },
  methods: {
    /** 查询表集合 */
    getList() {
      this.loadData(this.url.list);
    },

    /** 生成代码操作 */
    handleGenTable(row) {
      //生成到项目路径下
      if(row && row.genType === "2") {
        this.$confirm('确认将代码生成到项目路径下，已存在的同名文件将被覆盖?', "警告", {type: "warning"}).then(()=>{
          httpGet(this.url.genCode + row.id ).then(response => {
            this.msgSuccess("成功生成到自定义路径：" + row.genPath);
          });
        });
        return;
      }

      //生成代码并打包下载
      const ids = row.id || this.selectedRowKeys.join();
      if (!ids) {
        this.msgError("请选择表记录");
        return;
      }
      this.$refs.downloadIframe.download({tableIds: ids, s: 'gen_'+ids}, this.url.batchGenCode)
      // downloadFileHidden(this.url.batchGenCode, {tableIds: ids });
    },

    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },

    /** 预览按钮 */
    handlePreview(row) {
      this.loading = true;
      httpGet(this.url.previewCode + row.id).then(response => {
        this.$refs.preview.openDialog(response.data);
      }).finally(()=>{
	    	this.loading = false;
	    });
    },

    /** 修改按钮操作 */
    handleEditTable(row) {
      const id = row.id || this.selectedRowKeys[0];
      this.$router.push("/gen/editTable/" + id);
    },

    /** 从数据库同步表结构 */
    handleTableSync(row) {
      this.$confirm('确认要从数据库同步表结构?', "确认", {type: "warning"}).then(()=>{
        httpPost(this.url.syncFromDb + row.id).then(() => {
          this.msgSuccess("同步成功");
        }).catch(function() {});
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.selectedRowKeys;
      this.deleteData(this.url.base, ids);
    }

  }
};
</script>
